package com.antoco.controlcenter.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.view.View;

import androidx.core.graphics.drawable.DrawableCompat;

import com.antoco.controlcenter.base.BaseApplication;

import org.videolan.libvlc.media.MediaPlayer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BitmapUtil {

    /*
     *
     * @Title: bitmapRotation
     * @Description: 图片旋转
     * @param bm
     * @param orientationDegree
     * @return Bitmap
     * @throws
     */
    private static Bitmap rotateBitmap(Bitmap bm, int orientationDegree) {
        //方便判断，角度都转换为正值
        int degree = orientationDegree;
        if (degree < 0) {
            degree = 360 + orientationDegree;
        }

        int srcW = bm.getWidth();
        int srcH = bm.getHeight();

        Matrix m = new Matrix();
        m.setRotate(degree, (float) srcW / 2, (float) srcH / 2);
        float targetX, targetY;

        int destH = srcH;
        int destW = srcW;

        //根据角度计算偏移量，原理不明
        if (degree == 90) {
            targetX = srcH;
            targetY = 0;
            destH = srcW;
            destW = srcH;
        } else if (degree == 270) {
            targetX = 0;
            targetY = srcW;
            destH = srcW;
            destW = srcH;
        } else if (degree == 180) {
            targetX = srcW;
            targetY = srcH;
        } else {
            return bm;
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        //注意destW 与 destH 不同角度会有不同
        Bitmap bm1 = Bitmap.createBitmap(destW, destH, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);
        return bm1;
    }


    /**
     * 压缩图片
     *
     * @param bgimage
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        //matrix.postScale(scaleWidth, scaleHeight);//TODO 因为宽高不确定的因素,所以不缩放
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    /**
     * 截取指定View为图片
     *
     * @param view
     * @return
     * @throws Throwable
     */
    public static Bitmap captureView(View view) {
        Bitmap bm = null;
        try {
            bm = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
            view.draw(new Canvas(bm));
        } catch (Throwable throwable) {

        }
        return bm;
    }

    public static String saveBitmap(Bitmap bitmap) {
        if (null == bitmap) {
            ToastUtils.showToast(BaseApplication.getContext(), "图片未获取");
            return "";
        }
        File file = null;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyyHHmmss");
            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + formatter.format(new Date(System.currentTimeMillis())) + ".png";
            file = new File(path);
            if (!file.exists()) {
                OutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 80, out);
                out.flush();
                out.close();
            }
        } catch (IOException ioException) {
            ioException.fillInStackTrace();
        }

        return file.getAbsolutePath();
    }


    /**
     * 获取视频的缩略图
     * 先通过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图。
     * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的值，这样会节省内存。
     *
     * @param videoPath 视频的路径
     * @param width     指定输出视频缩略图的宽度
     * @param height    指定输出视频缩略图的高度度
     * @param kind      参照MediaStore.Images(Video).Thumbnails类中的常量MINI_KIND和MICRO_KIND。
     *                  其中，MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
     * @return 指定大小的视频缩略图
     */
    public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
        Bitmap bitmap = null;
        // 获取视频的缩略图
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
        if (bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }


    @SuppressLint("WrongConstant")
    public static Bitmap getVideoThumb(String path) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        return media.getFrameAtTime();
    }

    /**
     * @param path     视频的本地路径
     * @param position 视频流播放的position
     * @return Bitmap 返回的视频图像
     * @throws
     * @Title: getVideoFrame
     * @Description: 获取视频某帧的图像，但得到的图像并不一定是指定position的图像。
     */
    @SuppressLint("NewApi")
    public static Bitmap getVideoFrame(String path) {

        Bitmap bmp = null;
        // android 9及其以上版本可以使用该方法
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //视频uri
            retriever.setDataSource(path);
            //获取视频某个时间点帧图像
            bmp = retriever.getFrameAtTime(0);
        } catch (RuntimeException e) {
        }
        return bmp;
    }

    /**
     * @param uri         视频的本地路径
     * @param context     上下文
     * @param mediaPlayer 媒体播放Player
     * @return Bitmap 返回的视频图像
     */
    public static Bitmap getVideoFrame(Context context, String url, MediaPlayer mediaPlayer) {
        Bitmap bmp = null;
        // android 2.3及其以上版本使用
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(context, Uri.parse(url));
            // 这一句是必须的
            String timeString =
                    retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            // 获取总长度,这一句也是必须的
            long titalTime = Long.parseLong(timeString) * 1000;

            int duration = mediaPlayer.getDuration();
            // 通过这个计算出想截取的画面所在的时间
            long videoPosition = titalTime * mediaPlayer.getCurrentPosition() / duration;
            if (videoPosition > 0) {
                bmp = retriever.getFrameAtTime(videoPosition,
                        MediaMetadataRetriever.OPTION_CLOSEST);
            }
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.fillInStackTrace();
            }
        }
        return bmp;
    }

    /**
     * 修改drawable 的颜色
     */
    public static Drawable wrappedDrawable(Context context, Drawable drawable, int color) {
        ColorStateList csl = (ColorStateList) context.getResources().getColorStateList(color, null);
        Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTintList(wrappedDrawable, csl);
        return wrappedDrawable;
    }


}
